"use strict";

import { app, protocol, BrowserWindow, ipcMain, Menu, Tray } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
const shutdown = require("electron-shutdown-command");
const isDevelopment = process.env.NODE_ENV !== "production";
import path from "path";

const appFolder = path.dirname(process.execPath);
const updateExe = path.resolve(
  appFolder,
  "Vue-Electron-NeteaseCloudMusic Setup 0.1.0.exe"
);

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1030,
    height: 670,
    minWidth: 1030,
    minHeight: 670,
    frame: false,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    win.loadURL("app://./index.html");
  }

  //设置最小化、最大化、关闭
  ipcMain.on("minimize", function () {
    win.minimize();
  });

  ipcMain.on("close", function () {
    win.destroy();
  });

  ipcMain.on("window-max", function () {
    if (win.isMaximized()) {
      win.restore();
    } else {
      win.maximize();
    }
  });

  //设置开机自启动
  ipcMain.on("changeAutoStart-open", () => {
    console.log("changeAutoStart-open");
    app.setLoginItemSettings({
      openAtLogin: true,
      path: updateExe,
      args: [],
    });
  });

  ipcMain.on("changeAutoStart-closed", () => {
    console.log("changeAutoStart-closed");
    app.setLoginItemSettings({
      openAtLogin: false,
      path: updateExe,
      args: [],
    });
  });

  //设置定时关机
  ipcMain.on("changeTime", (event, arg) => {
    if (arg == 0) {
      shutdown.abort();
    } else {
      console.log("open");
      console.log(arg);
      shutdown.abort();
      shutdown.shutdown({
        timerseconds: arg,
      });
    }
  });

  ipcMain.on("closeShutDowm", () => {
    console.log("close");
    shutdown.abort();
  });

  //设置最小化托盘
  global.isHide = false;
  ipcMain.on("Tray", () => {
    if (global.isHide) {
      win.hide();
    } else {
      // 设置系统托盘图标
      const iconPath = path.join(
        __dirname,
        isDevelopment
          ? "../src/assets/wangyiyunIcon.png"
          : "./assets/wangyiyunIcon.png"
      );

      const appTray = new Tray(iconPath);

      // 图标的上下文菜单
      const contextMenu = Menu.buildFromTemplate([
        {
          label: "退出",
          icon: path.join(
            __dirname,
            isDevelopment ? "../src/assets/tuichu.png" : "./assets/tuichu.png"
          ),
          click: () => {
            win.destroy();
          },
        },
        {
          label: "设置",
          icon: path.join(
            __dirname,
            isDevelopment ? "../src/assets/shezhi.png" : "./assets/shezhi.png"
          ),
          click: () => {
            win.webContents.send("openSetUp");
            win.show();
          },
        },
        {
          label: "播放/暂停",
          icon: path.join(
            __dirname,
            isDevelopment ? "../src/assets/zhanting.png" : "./assets/zhanting.png"
          ),
          click: () => {
            win.webContents.send("toggle");
            win.show();
          },
        },
        {
          label: "打开/关闭歌词",
          icon: path.join(
            __dirname,
            isDevelopment ? "../src/assets/open.png" : "./assets/open.png"
          ),
          click: () => {
            win.webContents.send("Lyric");
            win.show();
          },
        },
        {
          label: "播放设置",
          icon: path.join(
            __dirname,
            isDevelopment ? "../src/assets/shezhi.png" : "./assets/shezhi.png"
          ),
          submenu: [
            {
              label: "列表播放",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/liebiao.png" : "./assets/liebiao.png"
              ),
              click: () => {
                win.webContents.send("bofang", 1);
                win.show();
              },
            },
            {
              label: "单曲播放",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/danqu.png" : "./assets/danqu.png"
              ),
              click: () => {
                win.webContents.send("bofang", 2);
                win.show();
              },
            },
            {
              label: "随机播放",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/suiji.png" : "./assets/suiji.png"
              ),
              click: () => {
                win.webContents.send("bofang", 3);
                win.show();
              },
            },
            {
              label: "顺序播放",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/shunxu.png" : "./assets/shunxu.png"
              ),
              click: () => {
                win.webContents.send("bofang", 4);
                win.show();
              },
            },
          ],
        },
        {
          label: "播放器设置",
          icon: path.join(
            __dirname,
            isDevelopment ? "../src/assets/shezhi.png" : "./assets/shezhi.png"
          ),
          submenu: [
            {
              label: "正常模式",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/zhengchang.png" : "./assets/zhengchang.png"
              ),
              click: () => {
                win.webContents.send("bofangQi", 1);
                win.show();
              },
            },
            {
              label: "mini模式",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/minimize.png" : "./assets/minimize.png"
              ),
              click: () => {
                win.webContents.send("bofangQi", 2);
                win.show();
              },
            },
            {
              label: "浮动模式",
              icon: path.join(
                __dirname,
                isDevelopment ? "../src/assets/float.png" : "./assets/float.png"
              ),
              click: () => {
                win.webContents.send("bofangQi", 3);
                win.show();
              },
            },
          ],
        },
      ]);

      // 展示主窗口，隐藏主窗口 mainWindow.hide()
      win.hide();
      global.isHide = true;

      // 设置托盘悬浮提示
      appTray.setToolTip("网易云音乐");

      // 设置托盘菜单
      appTray.setContextMenu(contextMenu);

      // 单击托盘小图标显示应用
      appTray.on("click", () => {
        // 显示主程序
        win.show();
        // 关闭托盘显示
        // appTray.destroy();
      });
    }
  });
}

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    console.log("open window");
  }
  createWindow();
  require("./electron-menu/electron-menu.js");
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
